package com.lmbsvn.front.shiro.realm;

import com.google.code.kaptcha.Constants;
import com.lmbsvn.core.shiro.bean.CaptchaException;
import com.lmbsvn.core.shiro.bean.UsernamePasswordCaptchaToken;
import com.lmbsvn.core.util.EncryptUtils;
import com.lmbsvn.core.util.SpringContextHolder;
import com.lmbsvn.front.model.Hd_svnuser;
import com.lmbsvn.front.service.Hd_svnuserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 用户和权限的认证
 * @author lumingbao
 */
public class ShiroRealm extends AuthorizingRealm{

	@Autowired
	private Hd_svnuserService userService;

	/**
	 * 认证回调函数, 登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException{

		UsernamePasswordCaptchaToken token = (UsernamePasswordCaptchaToken) authcToken;
		
		// 增加判断验证码逻辑
		String captcha = token.getCaptcha();
		String exitCode = SecurityUtils.getSubject().getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY).toString();
		if(captcha == null || !captcha.equals(exitCode)){
			throw new CaptchaException("captcha error.");
		}
		
		String username = token.getUsername();
		Hd_svnuser user = null;
		try {
			user = userService.getObjectByUsername(username);
		}catch (Exception e){
			e.printStackTrace();
		}
		
		if(user == null){
			throw new UnknownAccountException("Null usernames are not allowed by this realm."); //没找到帐号
		}
//		if(!"ryztqy".equals(user.getF_status())){
//			throw new LockedAccountException("Accounts are locked"); //帐号锁定
//		}

		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				user.getF_username(), //用户名
				user.getF_password(), //密码
				ByteSource.Util.bytes(token.getStrpassword()), //salt = Username + Salt (这里将用户的 登陆账号作为其加密的盐值)
				getName() //realm name
		);
		return authenticationInfo;
	}
	
	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String currentUsername = (String)super.getAvailablePrincipal(principals);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		return null;
	}
	
	/**
	 * 更新用户授权信息缓存.
	 */
    public void clearCachedAuthorizationInfo(String principal) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
        clearCachedAuthorizationInfo(principals);
    }
    
    public static void main(String[] args) {
    	System.out.println(EncryptUtils.md5Password("101202303", "101202303"));
	}
}
